﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using RgUtility.Orm;
using WanCommon.Entity;
using WanCommon;



namespace WanCommon.LogModule
{
   
    public class LogBll
    {
        /// <summary>
        /// 供应商用户类型
        /// </summary>
        public const string Supplier = "Supplier";
        /// <summary>
        /// 海关用户类型
        /// </summary>
        public const string Person = "Person";

        /// <summary>
        /// 未授权Web用户
        /// </summary>
        public const string UnAuthWeb = "UnAuthWeb";

        /// <summary>
        /// 授权的Web用户
        /// </summary>
        public const string AuthWechatWeb = "AuthWechatWeb";

        public List<LogView> GetLogLs()
        {
            using (var db = DbFactory.GetDb())
            {

                string sql =
                #region
 @"
 
select a.Id,a.Content,a.OperateTime,a.OperateUserId,
'供应商用户'  as OperateUserType,SupplierOut.Name as OperateUserName
from 
(
	select WanLog.*
	from Wanlog 
	where WanLog.OperateUserType='" + UserType.Supplier + @"'
) a
left join SupplierOut on  cast(a.OperateUserId as int)=SupplierOut.Id
union all
select a.Id,a.Content,a.OperateTime,a.OperateUserId,
'海关用户'  as OperateUserType,SupplierOut.Name as OperateUserName
from 
(
	select WanLog.*
	from Wanlog 
	where WanLog.OperateUserType='" + UserType.Person + @"'
) a
left join SupplierOut on  cast(a.OperateUserId as int)=SupplierOut.Id
union all
select a.Id,a.Content,a.OperateTime,a.OperateUserId,
'未授权网页用户'  as OperateUserType,SupplierOut.Name as OperateUserName
from 
(
	select WanLog.*
	from Wanlog 
	where WanLog.OperateUserType='" + UnAuthWeb + @"'
) a
left join SupplierOut on  cast(a.OperateUserId as int)=SupplierOut.Id
union all
select a.Id,a.Content,a.OperateTime,a.OperateUserId,
'授权微信用户'  as OperateUserType,SupplierOut.Name as OperateUserName
from 
(
	select WanLog.*
	from Wanlog 
	where WanLog.OperateUserType='" + AuthWechatWeb + @"'
) a
left join SupplierOut on  cast(a.OperateUserId as int)=SupplierOut.Id

";
                #endregion
                return db.Query<LogView>(sql, null);
            }
        }

        /// <summary>
        /// 请使用手动拼接Json的格式传入Content内容(拼接量少,格式比较好统一)如：
        /// 提交供供应商注册信息：{ 名称:XXX,ID:1}
        /// 为尽量不使用分布式事务协调器（有些互联网Windows不给开启）请以该方法的格式将日志代码写入Bll
        /// </summary>
        /// <param name="log"></param>
        public static void Write(Log log)
        {
            using (var db = DbFactory.GetDb())
            {
                db.From<Log>().Add(log,i=>i,i=>i.Id);
            }
        }
        /// <summary>
        /// 非分布式事务版
        /// </summary>
        /// <param name="db"></param>
        /// <param name="log"></param>
        public static void Write(DbContext db, Log log)
        {
            db.From<Log>().Add(log,i=>i,i=>i.Id);
        }

        
    }
}
